package aishua.com.mytestapplist;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.Signature;
import android.nfc.Tag;
import android.os.Environment;

import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.text.Html;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.zip.Inflater;

import aishua.com.mytestapplist.diyiview.CustomView;
import aishua.com.mytestapplist.diyiview.Myview;
import aishua.com.mytestapplist.extend.Child;
import aishua.com.mytestapplist.extend.Grandfather;
import aishua.com.mytestapplist.extend.Partent;
import aishua.com.mytestapplist.utils.LogUtils;

import static android.R.attr.path;
import static android.content.pm.PackageManager.GET_ACTIVITIES;

public class MainActivity extends Activity {
    private static final String TAG = "MainActivity-";
   private CustomView customView;
    private Myview btn_test;
    private Button btn_click;
    private LinearLayout ln_myline;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        verifyStoragePermissions(this);
        ln_myline = (LinearLayout) findViewById(R.id.ln_myline);
        customView = (CustomView) findViewById(R.id.customView);
        btn_test = (Myview) findViewById(R.id.btn_test);
        btn_click = (Button) findViewById(R.id.btn_click);
//        btn_click.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//
//
//                return false;
//            }
//        });
//        btn_test.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//                LogUtils.v(TAG + "onClick--" + v.getClass().getName());
////                openPlug("315041592E5359532E444446303201","com.ffcs.nfcplugin.wf",0);
////                String result = getPackageSha1(MainActivity.this,"cn.com.ctbri.pptoc");
////                LogUtils.v(TAG+"onClick--"+result);
//
//            }
//        });


//        btn_test.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                int e = event.getAction();
//                switch (e) {
//                    case MotionEvent.ACTION_DOWN:
//
//                        LogUtils.v(TAG + "onTouch()--MotionEvent.ACTION_DOWN");
////                        return false;
//                        break;
//                    case MotionEvent.ACTION_MOVE:
//
//                        LogUtils.v(TAG + "onTouch()--MotionEvent.ACTION_MOVE");
////                        return true;
//                        break;
//                    case MotionEvent.ACTION_UP:
//
//                        LogUtils.v(TAG + "onTouch()--MotionEvent.ACTION_UP");
////                        return true;
//                        break;
//                }
//                return false;
//            }
//        });
        customView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                LogUtils.v(TAG+"customView-onClick");
//              String result =  testSwitch();
//                testhttp();
//                LogUtils.v(TAG+"result---"+result);
//                testXutils();
                testdigui();
//                testExtend();
            }
        });
//        customView.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                int e = event.getAction();
//                switch (e) {
//                    case MotionEvent.ACTION_DOWN:
//
//                        LogUtils.v(TAG + "customView-onTouch()--MotionEvent.ACTION_DOWN");
////                        return true;
//                        break;
//                    case MotionEvent.ACTION_MOVE:
//
//                        LogUtils.v(TAG + "customView-onTouch()--MotionEvent.ACTION_MOVE");
////                        return true;
//                        break;
//                    case MotionEvent.ACTION_UP:
//
//                        LogUtils.v(TAG + "customView-onTouch()--MotionEvent.ACTION_UP");
////                        return true;
//                        break;
//                }
//                return false;
//            }
//        });

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int e = event.getAction();
        switch (e) {
            case MotionEvent.ACTION_DOWN:

                LogUtils.v(TAG + "MainActivity-onTouchEvent()--MotionEvent.ACTION_DOWN");
//                        return true;
                break;
            case MotionEvent.ACTION_MOVE:

                LogUtils.v(TAG + "MainActivity-onTouchEvent()--MotionEvent.ACTION_MOVE");
//                        return true;
                break;
            case MotionEvent.ACTION_UP:

                LogUtils.v(TAG + "MainActivity-onTouchEvent()--MotionEvent.ACTION_UP");
//                        return true;
                break;
        }

        return super.onTouchEvent(event);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        int e = ev.getAction();
        switch (e) {
            case MotionEvent.ACTION_DOWN:

                LogUtils.v(TAG + "MainActivity-dispatchTouchEvent()--MotionEvent.ACTION_DOWN");
//                        return true;
                break;
            case MotionEvent.ACTION_MOVE:

                LogUtils.v(TAG + "MainActivity-dispatchTouchEvent()--MotionEvent.ACTION_MOVE");
//                        return true;
                break;
            case MotionEvent.ACTION_UP:

                LogUtils.v(TAG + "MainActivity-dispatchTouchEvent()--MotionEvent.ACTION_UP");
//                        return true;
                break;
        }
        return super.dispatchTouchEvent(ev);
    }
    // Storage Permissions
//    private static final int REQUEST_EXTERNAL_STORAGE = 1;
//    private static String[] PERMISSIONS_STORAGE = {
//            Manifest.permission.READ_EXTERNAL_STORAGE,
//            Manifest.permission.WRITE_EXTERNAL_STORAGE };
//    /**
//     * Checks if the app has permission to write to device storage
//     * If the app does not has permission then the user will be prompted to
//     * grant permissions
//     * @param activity
//     */
//    public static void verifyStoragePermissions(Activity activity) {
//// Check if we have write permission
//        int permission = ActivityCompat.checkSelfPermission(activity,
//                Manifest.permission.WRITE_EXTERNAL_STORAGE);
//
//        if (permission != PackageManager.PERMISSION_GRANTED) {
//// We don't have permission so prompt the user
//            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
//                    REQUEST_EXTERNAL_STORAGE);
//        }
//    }


    public void openPlug(String appletAID, String appPacketName, int mode) {
       LogUtils.v("excuteSeOpr()-goto-openPlug()-mode=" + mode);
        if (appletAID == null) {
            return;
        }

        LogUtils.v("openPlug()-appletAID=" + appletAID);
        PackageInfo pi = null;
        try {
            PackageManager pManager = getPackageManager();
            pi = pManager.getPackageInfo(appPacketName,0);
            Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
            resolveIntent.setPackage(pi.packageName);
            List<ResolveInfo> apps = pManager.queryIntentActivities(
                    resolveIntent, 0);
            ResolveInfo ri = apps.iterator().next();
            if (ri != null) {
                String packageName = ri.activityInfo.packageName;
                String className = ri.activityInfo.name;
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.putExtra("AID", appletAID);
                intent.putExtra("startMode", mode);
                ComponentName cn = new ComponentName(packageName, className);
                intent.setComponent(cn);
                LogUtils.v("packageName---"+packageName+",className---"+className);
                startActivity(intent);
            }
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchElementException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public static String getPackageSha1(Context context, String packageName){
        if ("".equals(packageName)){
            return null;
        }
        try {
            /** 通过包管理器获得指定包名包含签名的包信息 **/
            PackageManager  manager =  context.getPackageManager();
            PackageInfo packageInfo = manager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
            /******* 通过返回的包信息获得签名数组 *******/
            Signature[] signatures = packageInfo.signatures;
            /******* 循环遍历签名数组拼接应用签名 *******/

            byte[] sign_bytes = signatures[0].toByteArray();
            return Encrypt(sign_bytes, "sha-1");
            //测试修改 下载长沙应用
//			   return "241C5343E7ED1309B01A78053857F564144645BE";
            /************** 得到应用签名 **************/
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String Encrypt(byte[] strSrc,String encName) {
        MessageDigest md = null;
        String strDes=null;
        try {
            if (encName==null||encName.equals("")) {
                encName="MD5";
            }
            md = MessageDigest.getInstance(encName);
            md.update(strSrc);
            strDes = bytesToHexString(md.digest());  //to HexString
        } catch (NoSuchAlgorithmException e) {
            return strDes;
        }
        return strDes;
    }
    public static String bytesToHexString(byte[] bytes) {

        if (bytes == null)
        {
            return "";
        }
        StringBuffer buff = new StringBuffer();
        int len = bytes.length;
        for (int j = 0; j < len; j++)
        {
            if ((bytes[j] & 0xff) < 16)
            {
                buff.append('0');
            }
            buff.append(Integer.toHexString(bytes[j] & 0xff));
        }
        return buff.toString().toUpperCase();
    }

    public String  testSwitch(){
        int i =2;
        switch (i){
            case 1:
                break;
            case 2:
                return "nihao";
        }
        return "good";
    }

    public void testhttp(){

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    //4.请求URL地址
                    //4.1创建URL对象
                    URL url = new URL("http://blog.csdn.net/guolin_blog/article/details/9097463");
                    Log.v(TAG,"result---"+"http://www.baidu.com");
                    //4.2获取Urlconnection对象
                    HttpURLConnection connection = (HttpURLConnection)url.openConnection();

                    //4.3为Urlconnection对象设置请求参数，请求方式，连接超时时间
                    connection.setRequestMethod("GET");//设置请求方式
                    connection.setConnectTimeout(1000*10);//设置超时时间

                    //4.4在获取url请求的数据提前需要判断响应码，200成功，206访问部分数据成功，300跳转或重定向，400错误，500服务器异常
                    int code = connection.getResponseCode();
                    Log.v(TAG,"result---"+code);
                    if (code == 200){
                        //4.5获取有效数据，并将获取的流数据分析成String
                        InputStream inputStream = connection.getInputStream();
//                        String result = StreamUtils.streamToString(inputStream);
                    }
                } catch (Exception e) {

                    e.printStackTrace();
                }
            }
        }).start();
    }
    public void testXutils(){

        HttpUtils httpUtils = new HttpUtils();
        String URL_m = "http://192.168.2.133:8080/a.exe";
         String APK_FILE_PATH = "/sdcard/a.exe";
        httpUtils.download(URL_m, APK_FILE_PATH,
                true, // 如果从请求返回信息中获取到文件名，下载完成后自动重命名。
                new RequestCallBack<File>() {

                    @Override
                    public void onStart() {
                        //testTextView.setText("conn...");
                    }
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {

                        //testTextView.setText(current + "/" + total);

                        Log.v("down", current + "/" + total);

                    }

                    @Override
                    public void onSuccess(ResponseInfo<File> responseInfo) {

                        Log.v("qweas", responseInfo + "");
                    }
                    @Override
                    public void onFailure(HttpException error, String msg) {

                        Log.v("qweas", msg + "");

                    }
                });
    }
      int i= 0;;
      boolean result = false;
      int j = 0;
     private Grandfather grandfather;
     public void testdigui(){

         grandfather = new Grandfather();
         grandfather.testdigui();

     }

    public void  testExtend(){

        Partent partent = new Child();
        partent.testthond();
    }


}
